package com.study03.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study03.entity.Perm;
import com.study03.entity.User;
import com.study03.mapper.PermMapper;
import com.study03.mapper.UserMapper;
import com.study03.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermMapper permMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User user = userMapper.selectOne(queryWrapper);
        if (user==null){
            throw  new UsernameNotFoundException("用户名未找到");
        }
        //根据用户名查找权限
        QueryWrapper<Perm> wrapper=new QueryWrapper<>();
        wrapper.eq("user_id",user.getId());
        List<Perm> perms = permMapper.selectList(wrapper);
        //权限标识
        List<String> permTags = perms.stream().map(Perm::getTag).collect(Collectors.toList());
        user.setAuthorities(AuthorityUtils.createAuthorityList(permTags));
        return user;
    }
}
